package com.rabbitmq.service.impl;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.service.RabbitService;
import com.yx.tool.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author yinxing
 * @date 2022-08-30
 */
@Service
@Slf4j
public class RabbitServiceImpl implements RabbitService {


    @Value("${yx.rabbitmq.host}")
    private String host;

    @Value("${yx.rabbitmq.username}")
    private String username;

    @Value("${yx.rabbitmq.password}")
    private String password;

    @Value("${yx.rabbitmq.port}")
    private int port;

    /**
     * 往rabbitmq里面发消息
     *
     * @param route_key
     * @param exchange_name
     * @return 自定义返回类
     * @throws IOException
     */
    @Override
    public Response sendMessage(String exchange_name, String route_key, String message) throws IOException {
        Channel channel = getChannel();
        channel.basicPublish(exchange_name, route_key, null,message.getBytes());
        log.info("推送消息完成");
        return Response.builder().code(0).message("push success").build();
    }

    /**
     * 获取信道
     *
     * @return 与rabbitmq之间的信道
     */
    public Channel getChannel() {
        try {
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setUsername(username);
            factory.setPassword(password);
            factory.setPort(port);
            //创建连接
            Connection connection = factory.newConnection();
            //创建信道
            Channel channel = connection.createChannel();
            return channel;
        } catch (Exception e) {
            System.out.println("rabbitmq链接有问题！！！");
        }
        return null;
    }
}
